var userInfos = {};
var openId = '';
var app = getApp();
Page({
    data: {
        bgHeight: '',
        mineHeight: '',
        mineWidth: '',
        btnWidth: '',
        screenWidth: '',
        userInfo: {},
        hasUserInfo: false,
        canIUseGetUserProfile: false,
    },
    onLoad() {
        if (wx.getUserProfile) {
            this.setData({
                canIUseGetUserProfile: true
            })
        }
    },
    //封装方法（拿取用户openid）
    getOpenid() {
        wx.cloud.callFunction({
            name: 'getOpenid'
        }).then(res => {
            console.log("调用成功", res);
            openId = res.result.openid
        }).catch(res => {
            console.log("调用失败", res);
        })
    },
    //封装用户数据上传数据库，先查询数据库是否有该用户信息，防止重复上传
    uploadUserInfo() {
        this.getOpenid();
        const db = wx.cloud.database()
        db.collection('userInfo').where({
            _openid: 'openId' // 填入当前用户 openid
        }).get().then(res => {
            console.log(res.data)
            if (res.data.length == 0) {
                console.log("正在上传");
                db.collection('userInfo').add({
                    data: {
                        avatarUrl: userInfos.avatarUrl,
                        nickName: userInfos.nickName
                    },
                    success: res => {
                        console.log('[数据库] [新增记录] 成功，记录 _id: ', res._id)
                    },
                    fail: err => {
                        console.error('[数据库] [新增记录] 失败：', err)
                    }
                })
            } else {
                console.log("已有数据，不再上传");
            }
        })
    },
    getUserProfile: function (e) {
        wx.getUserProfile({
            desc: '用于完善会员资料', // 声明获取用户个人信息后的用途，后续会展示在弹窗中，请谨慎填写
            success: (res) => {
                console.log(res);
                userInfos = res.userInfo;
                app.globalData.checkUserInfo = res.userInfo;
                wx.showToast({
                    title: '登陆中...',
                    icon: 'loading',
                })
                this.setData({
                    userInfo: res.userInfo,
                    hasUserInfo: true
                })
                this.uploadUserInfo()
                wx.hideToast()
            }
        });

    },
    onReady: function () {
        let that = this;
        // 获取系统信息
        wx.getSystemInfo({
            success: function (res) {
                // console.log(res);
                that.setData({
                    screenWidth: res.screenHeight,
                    bgHeight: res.screenHeight * 0.18,
                    mineHeight: res.screenHeight * 0.21,
                    mineWidth: res.screenWidth * 0.8
                });
            }
        });
        // 拿button的宽度
        const query = wx.createSelectorQuery();
        query.select('#btn').boundingClientRect();
        query.selectViewport().scrollOffset();
        query.exec(function (res) {
            // console.log(res);
            that.setData({
                btnWidth: res[0].width
            })
        })
    },
    mypaperInfo: function () {
        console.log(userInfos.nickName);
        if (userInfos.nickName == undefined) {
            // console.log(11);
            wx.showToast({
                icon: 'error',
                title: '请先登录',
            })
            return
        }
        wx.navigateTo({
            url: '../myPaper/myPaper',
        })
    },
    aboutusInfo: function () {
        wx.navigateTo({
            url: '../aboutUs/aboutUs',
        })
    },
    outOnline() {
        var that = this
        if (userInfos.nickName !== undefined) {
            wx.showModal({
                title: '提示',
                content: '确认退出嘛？',
                success(res) {
                    if (res.confirm) {
                        console.log('用户点击确定')
                        app.globalData.checkUserInfo = {}
                        userInfos = {}
                        that.setData({
                            userInfo: {},
                            hasUserInfo: false,
                        })
                        wx.showToast({
                            title: '退出成功',
                            duration: 1500
                        })
                    } else if (res.cancel) {
                        console.log('用户点击取消')
                    }
                }
            })
        } else {
            wx.showToast({
                icon: 'error',
                title: '请先登录',
                duration: 1500
            })
        }
    },
    /**
     * 生命周期函数--监听页面显示
     */
    onShow: function () {

    },


    /**
     * 页面上拉触底事件的处理函数
     */
    onReachBottom: function () {

    }

})